package main

import (
	"fmt"
	"math"
)

// 如何求数组中两个元素的最小距离

func main() {
	arr := []int{4, 5, 6, 4, 7, 4, 6, 4, 7, 8, 5, 6, 4, 3, 10, 8}
	num1 := 4
	num2 := 8
	fmt.Println(minDynDistance(arr, num1, num2))
}

func minDynDistance(arr []int, num1, num2 int) int {
	if arr == nil || len(arr) == 0 {
		return math.MaxInt64
	}

	lastPosition1 := -1
	lastPosition2 := -1

	minDistance := math.MaxInt64

	for i, v := range arr {
		if v == num1 {
			lastPosition1 = i
			if lastPosition2 >= 0 {
				minDistance = min(minDistance, lastPosition1-lastPosition2)
			}
		}
		if v == num2 {
			lastPosition2 = i
			if lastPosition1 >= 0 {
				minDistance = min(minDistance, lastPosition2-lastPosition1)
			}
		}
	}

	return minDistance
}

func min(num1, num2 int) int {
	if num1 < num2 {
		return num1
	} else {
		return num2
	}
}
